package com.lab.network.proxy;

import com.lab.logtrack.AppLog;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.utils.ThreadUtil;

import java.util.concurrent.CountDownLatch;

/**
 * Created by ak
 * 代理类,用于封装和组合底层功能模块,以提供适用于上层的API调用
 */
public abstract class Proxy {


    private IProxyCallback mProxyCallback;

    public Proxy() {}

    public Proxy(IProxyCallback proxyCallback) {
        mProxyCallback = proxyCallback;
    }

    public void setProxyCallback(IProxyCallback proxyCallback) {
        mProxyCallback = proxyCallback;
    }

    protected final boolean setProxyResult(final ProxyResult<?> result) {
        return setProxyResult(result, true);
    }

    protected final boolean setProxyResult(final ProxyResult<?> result, boolean shouldResponseOnUiThread) {
        if (shouldResponseOnUiThread) {
            if (ThreadUtil.isUIThread()) {
                if (null != mProxyCallback) {
                    return mProxyCallback.onProxyResult(result);
                }
            } else {
                final boolean[] proxyResult = new boolean[1];
                proxyResult[0] = true;
                final CountDownLatch countDownLatch = new CountDownLatch(1);
                ThreadUtil.MAIN_THREAD_HANDLER.post(new Runnable() {
                    @Override
                    public void run() {
                        if (null != mProxyCallback)
                            proxyResult[0] = mProxyCallback.onProxyResult(result);
                        countDownLatch.countDown();
                    }
                });
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    AppLog.w(e.getMessage());
                }
                return proxyResult[0];
            }
        } else {
            if (null != mProxyCallback) {
                return mProxyCallback.onProxyResult(result);
            }
        }
        return true;
    }

    public void clearProxyCallback() {
        mProxyCallback = null;
    }

}
